/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tamnhat.controller;

import com.tamnhat.entity.ContentTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.ServletContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Administrator
 */
public class DownloadTemplateController implements Serializable {

    private ContentTemplate current;
    private final String separator = System.getProperty("file.separator");
    private StreamedContent file;
    private DataModel items;

    /**
     * Creates a new instance of DownloadTemplateController
     */
    public DownloadTemplateController() {
        try{
            items = new ListDataModel(ContentTemplate.allCT(""));
        }catch(Exception e){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("ERROR: "+e.getMessage()));
            e.printStackTrace();
        }
    }

    public ContentTemplate getCurrent() {
        return current;
    }

    public void setCurrent(ContentTemplate current) {
        this.current = current;
    }

    public StreamedContent getFile() {
        try {
            current = (ContentTemplate) items.getRowData();
            String realUrl = separator + "dataExcell" + separator + current.getName() + ".xlsx";
            InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream(realUrl);
            String fileName = realUrl.replace(separator + "dataExcell" + separator, "");
            file = new DefaultStreamedContent(stream, "application/xlsx", fileName);                        
            return file;
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
            e.printStackTrace();
        }
        return null;
    }    
    public void setFile(StreamedContent file) {
        this.file = file;
    }

    public DataModel getItems() {
        return items;
    }

    public void setItems(DataModel items) {
        this.items = items;
    }
    
    public boolean check(){
        try {
            getFile();
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }
}
